<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户名称" prop="userName">
        <el-input v-model="queryParams.userName" placeholder="请输入用户名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="商品ID" prop="productId">
        <el-input v-model="queryParams.productId" placeholder="请输入商品ID" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="商品名称" prop="productName">
        <el-input v-model="queryParams.productName" placeholder="请输入商品名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="评分范围">
        <!-- 评分范围选择器（模仿时间范围选择器的布局和交互） -->
        <div class="rating-range-picker">
          <!-- 开始评分输入框 -->
          <el-input-number v-model="ratingRange[0]" :min="0" :max="100" :step="0.5" placeholder="最低评分"
            controls-position="right" class="range-input" @change="validateRange" />
          <!-- 分隔符（模仿时间范围的“-”） -->
          <span class="range-separator">-</span>
          <!-- 结束评分输入框 -->
          <el-input-number v-model="ratingRange[1]" :min="0" :max="100" :step="0.5" placeholder="最高评分"
            controls-position="right" class="range-input" @change="validateRange" />
        </div>
      </el-form-item>
      <el-form-item label="评论时间">
        <el-date-picker v-model="daterangeCreatedAt" style="width: 340px" value-format="yyyy-MM-dd HH:mm"
          type="datetimerange" range-separator="-" start-placeholder="开始日期时间" end-placeholder="结束日期时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['comment:comments:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['comment:comments:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['comment:comments:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['comment:comments:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="commentsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="评论ID" align="center" prop="id" />
      <el-table-column label="用户ID" align="center" prop="userId" />
      <el-table-column label="用户名称" align="center" prop="userName" />
      <el-table-column label="商品ID" align="center" prop="productId" />
      <el-table-column label="商品名称" align="center" prop="productName" />
      <!-- <el-table-column label="订单ID" align="center" prop="orderId" /> -->
      <el-table-column label="评分" align="center" prop="rating" />
      <el-table-column label="评论内容" align="center" prop="content" >
        <!-- 表格中展示富文本内容时使用v-html -->
        <template slot-scope="scope">
          <div v-html="scope.row.content" class="rich-text-preview"></div>
        </template>
      </el-table-column>

      <el-table-column label="评论图片" align="center" prop="imageUrlList">
        <template slot-scope="scope">
          <div v-if="scope.row.imageUrlList && scope.row.imageUrlList.length > 0">
            <el-image :src="scope.row.imageUrlList[0]" :preview-src-list="scope.row.imageUrlList"
              @click="openFullscreenViewer(scope.row.imageUrlList)" :width="50" :height="50" fit="cover"
              style="cursor: pointer"></el-image>
          </div>
          <span v-else>无图片</span>
        </template>
      </el-table-column>

      <el-table-column label="评论时间" align="center" prop="createdAt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['comment:comments:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['comment:comments:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改商品评论对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="商品ID" prop="productId">
          <el-input v-model="form.productId" placeholder="请输入商品ID" />
        </el-form-item>
        <el-form-item label="订单ID" prop="orderId">
          <el-input v-model="form.orderId" placeholder="请输入订单ID" />
        </el-form-item>
        <el-form-item label="评分" prop="rating">
          <el-input v-model="form.rating" placeholder="请输入评分" />
        </el-form-item>
        <el-form-item label="评论内容">
          <editor v-model="form.content" :min-height="192" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listComments,
    getComments,
    delComments,
    addComments,
    updateComments
  } from "@/api/comment/comments"

  export default {
    name: "Comments",
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 商品评论表格数据
        commentsList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 评论时间时间范围
        daterangeCreatedAt: [],
        // 评分分数范围
        ratingRange: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          userName: null,
          productId: null,
          productName: null,
          rating: null,
          createdAt: null,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          userId: [{
            required: true,
            message: "用户ID不能为空",
            trigger: "blur"
          }],
          productId: [{
            required: true,
            message: "商品ID不能为空",
            trigger: "blur"
          }],
          rating: [{
            required: true,
            message: "评分不能为空",
            trigger: "blur"
          }],
          createdAt: [{
            required: true,
            message: "评论时间不能为空",
            trigger: "blur"
          }],
          del: [{
            required: true,
            message: "删除标志(0存在)不能为空",
            trigger: "blur"
          }]
        }
      }
    },
    created() {
      this.getList()
    },
    methods: {
      // 验证评分范围有效性（开始值 ≤ 结束值）
      validateRange() {
        const [begin, end] = this.ratingRange;
        if (begin !== undefined && end !== undefined && begin > end) {
          // 自动交换值，确保范围合理
          this.ratingRange = [end, begin];
        }
      },
      /** 查询商品评论列表 */
      getList() {
        this.loading = true
        this.queryParams.params = {}
        if (null != this.ratingRange && '' != this.ratingRange) {
          this.queryParams.params["beginRating"] = this.ratingRange[0]
          this.queryParams.params["endRating"] = this.ratingRange[1]
        }
        if (null != this.daterangeCreatedAt && '' != this.daterangeCreatedAt) {
          this.queryParams.params["beginCreatedAt"] = this.daterangeCreatedAt[0]
          this.queryParams.params["endCreatedAt"] = this.daterangeCreatedAt[1]
        }
        listComments(this.queryParams).then(response => {
          this.commentsList = response.rows
          this.total = response.total
          this.loading = false
        })
      },
      // 取消按钮
      cancel() {
        this.open = false
        this.reset()
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          userId: null,
          productId: null,
          orderId: null,
          rating: null,
          content: null,
          createdAt: null,
          del: null
        }
        this.resetForm("form")
      },
      /** 搜索按钮操作 */
      handleQuery() {
        // 1. 处理评分范围：从数组拆分为 beginRating 和 endRating
        const [beginRating, endRating] = this.ratingRange;
        // 2. 处理时间范围：从数组拆分为 beginCreatedAt 和 endCreatedAt
        const [beginCreatedAt, endCreatedAt] = this.daterangeCreatedAt || [];

        // 3. 构建查询参数（与后端接口字段对应）
        const queryParams = {
          beginRating: beginRating || null,
          endRating: endRating || null,
          beginCreatedAt: beginCreatedAt || null,
          endCreatedAt: endCreatedAt || null
          // 其他参数...
        };

        this.queryParams.pageNum = 1
        this.getList()
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.ratingRange = [];
        this.daterangeCreatedAt = []
        this.resetForm("queryForm")
        this.handleQuery()
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset()
        this.open = true
        this.title = "添加商品评论"
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset()
        const id = row.id || this.ids
        getComments(id).then(response => {
          this.form = response.data
          this.open = true
          this.title = "修改商品评论"
        })
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateComments(this.form).then(response => {
                this.$modal.msgSuccess("修改成功")
                this.open = false
                this.getList()
              })
            } else {
              addComments(this.form).then(response => {
                this.$modal.msgSuccess("新增成功")
                this.open = false
                this.getList()
              })
            }
          }
        })
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids
        this.$modal.confirm('是否确认删除商品评论编号为"' + ids + '"的数据项？').then(function() {
          return delComments(ids)
        }).then(() => {
          this.getList()
          this.$modal.msgSuccess("删除成功")
        }).catch(() => {})
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('comment/comments/export', {
          ...this.queryParams
        }, `comments_${new Date().getTime()}.xlsx`)
      }
    }
  }
</script>
<style scoped>
  /* 评分范围选择器容器 */
  .rating-range-picker {
    display: inline-flex;
    align-items: center;
    width: 200px;
    /* 与时间选择器宽度一致 */
  }

  /* 输入框样式 */
  .rating-range-picker .range-input {
    width: 90%;
    /* 左右输入框各占45%宽度 */
  }

  /* 分隔符样式（模仿时间范围的“-”） */
  .rating-range-picker .range-separator {
    width: 10%;
    /* 分隔符占10%宽度 */
    text-align: center;
    color: #c0c4cc;
    /* 与Element默认分隔符颜色一致 */
  }

  /* 聚焦时的样式统一 */
  .rating-range-picker .el-input-number__input:focus {
    border-color: #409eff;
    /* 与时间选择器聚焦边框色一致 */
  }


  /* 富文本预览容器 */
  .rich-text-preview {
    max-width: 500px;
    padding: 5px;
    overflow: hidden;
  }

  /* 关键：使用深度选择器穿透 scoped 限制 */
  ::v-deep .rich-text-preview img {
    max-width: 100% !important;
    height: auto !important;
    max-height: 150px !important;
    object-fit: contain;
    /* 保持图片比例，不裁剪 */
    display: block;
    margin: 0 auto;
  }

  /* 处理可能的内联样式优先级问题 */
  ::v-deep .rich-text-preview img[style] {
    width: auto !important;
    /* 覆盖内联 width */
  }
</style>
